module mem_mux (
    input clk,
    input resetn,
    input [31:0] cpu_mem_addr,
    input [31:0] cpu_mem_wdata,
    input [3:0]  cpu_mem_wstrb,
    output        cpu_mem_ready,
    output [31:0] cpu_mem_rdata,
    input        cpu_mem_valid,
    input         cpu_mem_instr,
    
    input [31:0] dbg_mem_addr,
    input [31:0] dbg_mem_wdata,
    input [3:0]  dbg_mem_wstrb,
    output        dbg_mem_ready,
    output [31:0] dbg_mem_rdata,
    input        dbg_mem_valid,

    output [31:0] slave_mem_addr,
    output [31:0] slave_mem_wdata,
    output [3:0]  slave_mem_wstrb,
    input        slave_mem_ready,
    input [31:0] slave_mem_rdata,
    output        slave_mem_valid,
    output        slave_mem_instr//

);
reg [1:0] select;
reg mux_state;

assign slave_mem_valid = select[0] ? cpu_mem_valid : 
                            select[1] ? dbg_mem_valid : 1'b0;

assign slave_mem_instr = select[0] ? cpu_mem_instr : 1'b0;

assign slave_mem_addr = select[0] ? cpu_mem_addr :
                        select[1] ? dbg_mem_addr : 32'hzzzzzzzz;

assign slave_mem_wdata = select[0] ? cpu_mem_wdata :
                            select[1] ? dbg_mem_wdata : 32'hzzzzzzzz;

assign slave_mem_wstrb = select[0] ? cpu_mem_wstrb :
                            select[1] ? dbg_mem_wstrb : 4'b0000;

assign cpu_mem_ready = select[0] ? slave_mem_ready : 1'b0;
assign cpu_mem_rdata = select[0] ? slave_mem_rdata : 32'hzzzzzzzz;

assign dbg_mem_ready = select[1] ? slave_mem_ready : 1'b0;
assign dbg_mem_rdata = select[1] ? slave_mem_rdata : 32'hzzzzzzzz;

localparam mux_idle = 1'b0;
localparam mux_wait = 1'b1;
always @(posedge clk or negedge resetn) begin
    if(!resetn) begin
        select <= 2'b0;
        mux_state <= mux_idle;
    end
    else begin
        if(mux_state == mux_idle) begin
            casex({dbg_mem_valid,cpu_mem_valid})
                2'bx1:begin//01 11 cpu优先取指令
                    select <= 2'b01;
                    mux_state <= mux_wait;
                end
                2'b10:begin
                    select <= 2'b10;
                    mux_state <= mux_wait;
                end
                default:begin
                    select <= 2'b00;
                    mux_state <= mux_idle;
                end
            endcase
        end
        else begin
            if(slave_mem_ready) begin
                select <= 2'b00;
                mux_state <= mux_idle;
            end
            else begin
                select <= select;
                mux_state <= mux_state;
            end
        end
    end
end
endmodule